package cn.com.cetccst.appstore.ui.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;

import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.jssdk.CXJSInterface;
import cn.com.cetccst.appstore.jssdk.viewmodel.JSSDKViewModel;

public class PlatformWebActivity extends BaseWebActivity {
    public static String TAG = "WebActivity";
    private static final String CUSTOM_USER_AGENT = "Platform/EMM_ANDROID";
    public static final String KEY_APP_KEY = "emm_platform_auth_appId";
    public static final String KEY_CONTEXT_PARAMS = "emm_platform_context_params";
    private String mAppKey;
//    private JSFileChooserHelper mFileChooserHelper;
    private JSSDKViewModel jsSdkViewModel;
    private String contextParams;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_platform);
        getIntentData();
        jsSdkViewModel = new ViewModelProvider(this).get(JSSDKViewModel.class);
        initUI();
        initWebView();
    }

    protected void initUI() {
        mTopToolbar = findViewById(R.id.web_toolbar);
        mRootView = findViewById(R.id.web_root_view);
        mProgressView = findViewById(R.id.refreshing);
        mWebView = findViewById(R.id.webView);
        mWebView.setBackgroundColor(getResources().getColor(R.color.white));
    }

    @Override
    protected void getIntentData() {
        super.getIntentData();
        Intent intent = getIntent();
        mAppKey = intent.getStringExtra(KEY_APP_KEY);

        isCanOpenByBrowser = intent.getBooleanExtra("isCanOpenByBrowser", true);
        if (intent.hasExtra(KEY_CONTEXT_PARAMS)) {
            contextParams = intent.getStringExtra(KEY_CONTEXT_PARAMS);
        } else {
            contextParams = "{}";
        }
    }

    @Override
    protected void initWebView() {
        setWebChromeClient(new PlatformWebChromeClient()); // 设置setWebChromeClient对象
        setWebViewClient(new PlatformWebViewClient());
        setWebDownloadListener(new PlatformWebDownloadListener());
        super.initWebView();
        mWebView.addJavascriptInterface(new CXJSInterface(this, mWebView, contextParams), CXJSInterface.functionDomain);
        mWebView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                final WebView.HitTestResult hitTestResult = mWebView.getHitTestResult();
                // 如果是图片类型或者是带有图片链接的类型
                if (hitTestResult != null && (hitTestResult.getType() == WebView.HitTestResult.IMAGE_TYPE || hitTestResult.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE)) {
                    //异步检测是否是二维码，然后构造Dialog
                    handleImageLongClick(hitTestResult.getExtra());
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 网页回退
     *
     * @return
     */
    public boolean onKeyDown() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();//返回上一页面
            return true;
        }
        return false;
    }

    @Override
    protected void initWebSetting() {
        super.initWebSetting();
        String userAgent = mWebView.getSettings().getUserAgentString();
        mWebView.getSettings().setUserAgentString(userAgent + " " + CUSTOM_USER_AGENT);
    }

    @Override
    protected void webPageTitleLoaded(String loadedTitle) {
        super.webPageTitleLoaded(loadedTitle);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        jsSdkViewModel.destory(this, mAppKey);
    }

    @Override
    public void onPause() {//继承自BaseWebActivity
        super.onPause();
    }

    @Override
    public void onResume() {//继承自BaseWebActivity
        super.onResume();
    }

    /**
     * 下载、Blob图片
     *
     * @param url
     */
    protected void downBlobUrl(String url) {
        if (url.startsWith("blob")) {
            String blob = "  var request = new XMLHttpRequest();" +
                    "        request.open('GET', '" + url + "', true);" +
                    "        request.setRequestHeader('Content-type', 'text/plain');" +
                    "        request.responseType = 'blob';" +
                    "        request.onload = function (e) {" +
                    "            console.log('执行测试:'+this.status);" +
                    "            if (this.status === 200) {" +
                    "                var blobFile = this.response;" +
                    "                var reader = new FileReader();" +
                    "                reader.readAsDataURL(blobFile);" +
                    "                reader.onloadend = function() {" +
                    "                var base64data = reader.result;" +
                    "                window.java.saveBase64Image(base64data);" +
                    "                }" +
                    "             }" +
                    "        };" +
                    "        request.send();";

            String js = "javascript:" + blob;
            mWebView.loadUrl(js);
        }
    }

    private boolean isBlobUrl(String url) {
        return !TextUtils.isEmpty(url) && url.startsWith("blob:");
    }

    private void handleImageLongClick(final String extraData) {
//        final String[] items = new String[]{getString(R.string.save_image_to_local)};
//        final MenuListPopupWindow window = new MenuListPopupWindow(this, new MenuListPopupWindow.PopWindowEventListener() {
//            @Override
//            public void onPopItemClick(String itemString, int position, Object data) {
//                String itemName = data.toString();
//                if (itemName.equals(getString(R.string.save_image_to_local))) {
//                    if (isBlobUrl(extraData)) {
//                        downBlobUrl(extraData);
//                    } else {
////                        handleSaveWebImage(extraData);
//                    }
//                }
//            }
//
//            @Override
//            public void onPopDismiss(String tag) {
//
//            }
//        }, "", items, null);
//        window.setWidthAndHeight(400, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//        window.setBackground(R.drawable.popup_menu_round_top_background);
//        window.setBackgroundAlpha(getWindow(), 0.55f);
//        window.setAnimationStyle(com.westone.cx.commonsdk.R.style.bottom_popwin_anim_style);
//        window.resetItemTextGravity(Gravity.CENTER);
//        window.showAtLocation(mRootView, Gravity.BOTTOM, 0, 0);
    }

    /**
     * 网页中存在链接，可以点击下载文件的功能
     */
    protected class PlatformWebDownloadListener extends CXBaseWebDownloadListener {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            super.onDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength);
        }
    }

    /**
     * Listener for load states
     */
    protected class PlatformWebViewClient extends CXBaseWebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        //加载https时候，需要加入 下面代码
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
        }

        @Override
        @TargetApi(Build.VERSION_CODES.M)
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        // 旧版本，会在新版本中也可能被调用，所以加上一个判断，防止重复显示
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }
    }

    protected class PlatformWebChromeClient extends CXBaseWebChromeClient {
        @Override
        public void onReceivedTitle(WebView view, String title) {//显示标题
            super.onReceivedTitle(view, title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }


        @Override
        public boolean onShowFileChooser(WebView mWebView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
//            mFileChooserHelper = new JSFileChooserHelper(PlatformWebActivity.this, filePathCallback, fileChooserParams);
//
//            mFileChooserHelper.takeFile(fileChooserParams.getAcceptTypes());
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
        }
    }
}
